package com.example.java_chatroom.api;


import com.example.java_chatroom.model.User;
import com.example.java_chatroom.model.UserMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;



//登录
@RestController//表示该类是一个控制器，并且所有的方法返回值都将直接写入HTTP响应体中
public class UserAPI {
    @Resource//默认按照名字装配Bean
    UserMapper userMapper;

    @PostMapping("/login")
    @ResponseBody
    public Object login(String username, String password, HttpServletRequest req){
        //1.先去数据库中查，看username能否找到对应的user对象
        User user = userMapper.selectByName(username);
        if(user == null || !user.getPassword().equals(password)){
            System.out.println("登录失败，用户名或者密码错误！"+ user);
            return new User();
        }

        //2.如果都匹配，就登录成功，创建会话
        HttpSession session = req.getSession(true);
        session.setAttribute("user",user);
        //在返回前把password替换掉
        user.setPassword("");
        return user;
    }



//注册
    @PostMapping("/register")
    @ResponseBody
    public Object register(String username,String password){
        User user = null;
        try {
            user = new User();
            user.setUsername(username);
            user.setPassword(password);
            int ret = userMapper.insert(user);
            System.out.println("注册ret：" + ret);
            user.setPassword("");
        }catch (DuplicateKeyException e){
            //如果insert方法抛出上述异常，说明名字重复了
            user = new User();
            System.out.println("注册失败！username =" + username);
        }
        return user;
    }

//实现页面获取到当前的登录用户信息
    @GetMapping("/userInfo")
    @ResponseBody
    public Object getUserInfo(HttpServletRequest req){
        //1.先从请求中获取到会话
        HttpSession session = req.getSession(false);
        if (session == null){
            //会话不存在，用户尚未登录
            System.out.println("[getUserInfo] 当前获取不到 session 对象！");
            return new User();
        }
        //2.从会话中获取到之前保存的用户对象
        User user = (User) session.getAttribute("user");
        if (user == null){
            System.out.println("[getUserInfo] 当前获取不到 user 对象");
            return new User();
        }
        user.setPassword("");//隐藏密码
        return user;
    }
}
